﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Client.XML;

namespace Client.UserControls
{
    [ToolboxItem(true)]
    public partial class WorkPlan : UserControl
    {
        public WorkPlan()
        {
            InitializeComponent();
            this.workPlanItem1.ParentWP = this;
        }

        Point basePoint;
        public List<WorkPlanItem> lstItem = new List<WorkPlanItem>();

        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddWorkPlanItem(null);
        }

        private const int OFF_SET = 190 - 35;
        /// <summary>
        /// 添加计划项
        /// </summary>
        private void AddWorkPlanItem(PlanItem pItem)
        {
            WorkPlanItem item = new WorkPlanItem(this);
            item.Visible = true;
            this.Controls.Add(item);
            lstItem.Add(item);
            item.Location = new Point(basePoint.X, (lstItem.Count - 1) * OFF_SET);
            this.btnAdd.Location = new Point(basePoint.X, (lstItem.Count) * OFF_SET);
            this.Size = new Size(this.Width, this.Height + item.Height);

            if (pItem != null)
            {
                item.FillPlanItem(pItem);
            }
        }

        /// <summary>
        /// 获取当日计划项列表
        /// </summary>
        /// <returns></returns>
        public List<PlanItem> GetPlanItems()
        {
            List<PlanItem> ret = new List<PlanItem>();
            foreach (WorkPlanItem item in this.lstItem)
            {
                ret.Add(item.GetPlanItem());
            }

            return ret;
        }

        /// <summary>
        /// 填充计划
        /// </summary>
        /// <param name="pDayPlan"></param>
        public void FillPlan(DayPlan pDayPlan)
        {
            if(pDayPlan == null || pDayPlan.PlanItems.Count == 0)
                return;

            this.workPlanItem1.FillPlanItem(pDayPlan.PlanItems[0]);
            for (int i = 1; i < pDayPlan.PlanItems.Count; i++)
            { 
                this.AddWorkPlanItem(pDayPlan.PlanItems[i]);
            }
        }

        private void WorkPlan_Load(object sender, EventArgs e)
        {
            //this.basePoint = this.workPlanItem1.Location;
            lstItem.Add(this.workPlanItem1);
        }

        private bool IsAllInputValidate()
        {
            bool flag = true;
            foreach (var item in this.lstItem)
            {
                if (!item.IsValidate())
                {
                    flag = false;
                    break;
                }
            }

            return flag;
        }

        public bool IsValidateAndReOrder()
        {
            // 1.校验控件输入内容是否合法
            if (!this.IsAllInputValidate()) return false;

            bool flag = true;
            // 2. 按照日期重排计划并显示
            this.ReOrderWorkPlanItem();

            // 3. 校验时间是否有重叠的地方
            List<PlanItem> templst = this.GetPlanItems();
            // 获取排好序的PlanItem（用来和排好序的WorkPlanItem进行日期比较）
            List<PlanItem> templstForOrder = this.GetPlanItems().OrderBy(item => item.StartTime).ToList();
            
            // 让WorkPlanItem的日期和List<PlanItem>中的对象进行比较，看看是否有日期重叠的情况
            for (int j =0 ;j<this.lstItem.Count();j++)
            {   
                var item = this.lstItem[j];
                for(int i = 0; i< templst.Count; i++)
                {
                    // i，j相等意味着同一个控件，所以跳过比较
                    if (i == j) continue;
                    var temp = templst[i];
                    if ((DateTime.Parse(temp.StartTime).Ticks <= DateTime.Parse(item.StartTime).Ticks &&
                        DateTime.Parse(temp.EndTime).Ticks <= DateTime.Parse(item.StartTime).Ticks))
                    {
                        flag = true;
                        item.ClearError(PlanItemInputType.StartTime);
                    }
                    else if (DateTime.Parse(temp.StartTime).Ticks >= DateTime.Parse(item.StartTime).Ticks &&
                        DateTime.Parse(temp.StartTime).Ticks >= DateTime.Parse(item.EndTime).Ticks)
                    {   
                        flag = true;
                        item.ClearError(PlanItemInputType.StartTime);
                    }
                    else
                    {
                        flag = false;
                        item.SetError(PlanItemInputType.StartTime, "设置的时间段有重叠");
                        break;
                    }
                }

                if (!flag) break;
            }

            return flag;
        }

        /// <summary>
        /// 依据时间重新排列计划顺序
        /// </summary>
        /// <param name="pLst"></param>
        private void ReOrderWorkPlanItem()
        {
            List<PlanItem> templstForOrder = this.GetPlanItems().OrderBy(item => item.StartTime).ToList();
            for (int i = 0; i < templstForOrder.Count; i++)
            {
                this.lstItem[i].SetWorkPlanItem(templstForOrder[i]);
            }
        }

        public void DeleteWorkPlanItem(WorkPlanItem pItem)
        {
            // 参数为空或者列表数为1，不进行删除操作
            if (pItem == null || this.lstItem.Count == 1) return;
            
            // 不是最后一个元素，删除后其后元素位移上行
            int itemIndex = this.lstItem.IndexOf(pItem);
            if (itemIndex != this.lstItem.Count - 1)
            { 
                for(int i = this.lstItem.Count-1; i> itemIndex ;i--)
                {
                    var item = this.lstItem[i];
                    item.Location = new Point(item.Location.X, item.Location.Y - OFF_SET);
                }
            }
            this.lstItem.Remove(pItem);
            pItem.Dispose();
            this.btnAdd.Location = new Point(btnAdd.Location.X, btnAdd.Location.Y - OFF_SET);
        }
    }
}
